package com.fancoder.kafka;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class ProducerPartitioner implements Partitioner {
    private AtomicInteger currPartition = new AtomicInteger(0);

    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topic);
        if (keyBytes == null) {
            return currPartition.getAndIncrement() % partitionInfos.size();
        }
        return key.hashCode() % partitionInfos.size();
    }

    public void close() {

    }

    public void configure(Map<String, ?> map) {

    }
}
